package misc;



import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PageLoadListener implements PhaseListener {

	/**
 <lifecycle>
  <phase-listener>controler.PageLoadListener</phase-listener>
 </lifecycle>
	 */
	private static final long serialVersionUID = 5987064120063340539L;
	protected final static Log logger = LogFactory
			.getLog(PageLoadListener.class);

	public void afterPhase(PhaseEvent phaseEvent) {
		FacesContext facesContext = phaseEvent.getFacesContext();
		String viewId = phaseEvent.getFacesContext().getViewRoot().getViewId();
		
		viewId = viewId.substring(viewId.lastIndexOf('/')+1,viewId.length());
		
		
		//System.out.println(viewId);

		if (viewId.endsWith(".jsp")) {
			String managedBeanName = getManagedBeanNameFromView(viewId); //pc_Pages/inputusername
			Object object = facesContext.getApplication().createValueBinding(
					"#{" + managedBeanName + "}").getValue(facesContext);
			if (object == null)
				logger
						.error("OnPageLoad cannot be executed, no such managed bean:"
								+ managedBeanName);
			else {
				ILifeCycleAware lifeCycleAwareBean = (ILifeCycleAware) object;
				lifeCycleAwareBean.onPageLoad();
			}
		}
	}

	public void beforePhase(PhaseEvent phaseEvent) {

	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

	public static String capitalize(String s) {
		if (s.length() == 0)
			return s;
		return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
	}

	public String getManagedBeanNameFromView(String viewId) {
		String pageName = viewId.substring(0, viewId.length() - 4);
		return "pc_" + capitalize(pageName);
	}

}
